package com.huibao.hulibao.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.activity.LoginActivity;
import com.huibao.hulibao.activity.MainActivity;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;

import pdautils.PdaPrint;

/**
 * Created by lizhaoyong on 2018/5/7.
 */
public class CustomerManagerWebViewFragmentView extends Fragment {

    private Context context;
    public MainActivity mainActivity;

    public ImageView iv_back;
    public WebView wb_detail;
    public TextView tv_title;
    public RelativeLayout rl_base_title;

    public LoginEntity le;

    protected static final String APP_CACHE_DIRNAME = "/cache_path";
    private String url;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_webview_detail, null);
        context = getActivity();
        mainActivity = (MainActivity) getActivity();
        initView(v);
        initData();
        return v;
    }


    private void initData() {

        le = (LoginEntity) PreUtils.getObject(context, "LoginEntity");
        url = GlobalConstants.HOST + "/AppWap/PDA_APP/CRM/Index.aspx?ss=" + le.Message.Session;


        wb_detail.loadUrl(url);

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wb_detail.canGoBack()) {
                    wb_detail.goBack();// 返回前一个页面
                }
            }
        });
    }



    public void initWebView() {
        wb_detail.getSettings().setJavaScriptEnabled(true);
        wb_detail.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT,无网络时，使用LOAD_CACHE_ELSE_NETWORK
        // 开启DOM storage API 功能
        wb_detail.getSettings().setDomStorageEnabled(true);
        // 开启database storage API功能
        wb_detail.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = context.getFilesDir().getAbsolutePath()
                + APP_CACHE_DIRNAME;
        // Log.i(TAG, cacheDirPath);
        // 设置数据库缓存路径
        wb_detail.getSettings().setDatabasePath(cacheDirPath); // API 19
        // deprecated
        // 设置Application caches缓存目录
        wb_detail.getSettings().setAppCachePath(cacheDirPath);
        // 开启Application Cache功能
        wb_detail.getSettings().setAppCacheEnabled(true);

        // Log.i(TAG, wb_detail.getSettings().getDatabasePath());

    }

    public class JavaScriptinterface {

        private Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        public JavaScriptinterface(Context c) {
            mContext = c;
        }

        @JavascriptInterface
        public void pdaPrint(String msg) {
            pdautils.PdaPrint.printMsg(msg, mContext.getApplicationContext());
        }
    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    @JavascriptInterface
    private void initView(View v) {
        tv_title = (TextView) v.findViewById(R.id.tv_title);
        tv_title.setText(R.string.kehuguanli);

        wb_detail = (WebView) v.findViewById(R.id.wv_detail);
        rl_base_title = (RelativeLayout) v.findViewById(R.id.rl_base_title);
        iv_back = (ImageView) v.findViewById(R.id.iv_back);
        rl_base_title.setVisibility(View.VISIBLE);


        // 不使用缓存：
        // webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // webSettings.setJavaScriptEnabled(true);
        initWebView();
        // 让JS调用Android的方法
        wb_detail.addJavascriptInterface(new JavaScriptinterface(mainActivity), "android");
        wb_detail.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.d("url = " + url);

                if (url.contains(GlobalConstants.WEB_NAV) && !url.contains(GlobalConstants.WEB_NO_NAV)) {
                    // 显示导航栏
                    rl_base_title.setVisibility(View.VISIBLE);
                } else if (url.contains(GlobalConstants.WEB_NO_NAV)) {
                    // 不显示导航栏
                    rl_base_title.setVisibility(View.GONE);
                } else if (url.contains(GlobalConstants.WEN_CLOSE)) {
                    // 退出当前webview
                } else if (url.contains(GlobalConstants.WEN_lOGIN)) {
                    // 退出登录 去登录页面
                    PreUtils.saveObject(context, "LoginEntity", null);
                    Intent intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                }


                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Toast.makeText(context, R.string.wangluobuhao,
                        Toast.LENGTH_SHORT).show();
            }
        });
        wb_detail.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                result.confirm();
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message,
                                      String defaultValue, JsPromptResult result) {
                // TODO Auto-generated method stub
                return super.onJsPrompt(view, url, message, defaultValue,
                        result);
            }

        });
        wb_detail.loadUrl(url);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
